<template>
  <div>
    <!-- 查询参数及按钮部分 -->
    <div class="filter-container">
      <el-dialog  v-dialogDrag  
        title="查询"
        :visible.sync="dialogQueryFormVisible"
        style="padding:0px"
        width="50%"
      >
        <el-form
          ref="dataForm"
          class="dialog-Backgroundcolor"
          :model="listQuery"
          label-position="right"
          label-width="100px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="变动情况：">
                <el-select v-model="listQuery.changes" class="filter-item" clearable placeholder="--请选择--">
                  <el-option v-for="item in changeAgencys" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="人员类型：">
                <el-select v-model="listQuery.personType" class="filter-item" placeholder="--请选择--">
                  <el-option label="全部人员" value="" />
                  <el-option label="在职人员" value="3" />
                  <el-option label="离休人员" value="1" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="工资类型：">
                <el-select v-model="listQuery.salaryType" class="filter-item" clearable placeholder="--请选择--">
                  <el-option v-for="item in salaryTypes" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名：">
                <el-input v-model="listQuery.personName" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="身份证号码：">
                <el-input v-model="listQuery.idenNo" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-button size="small" class="filter-item" style="margin-left: 10px; float:right" type="primary" @click="handleQuery">
              查询
            </el-button>
          </el-row>
        </el-form>
      </el-dialog>
      <el-row>
        <el-col :span="12">
        <el-select
          v-model="formData.salaryType"
          class="filter-item"
          placeholder="--请选择--"
          @change="handleFilter"
        >
          <el-option label="全部人员" value="" />
          <el-option label="行政人员" value="0" />
          <el-option label="事业人员" value="1" />
          <el-option label="离休人员" value="11" />
        </el-select>
      </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div>单位名称：{{ unitName }}</div>
          <span style="font-size:16px">在编实发合计：{{ Number(reallySendSalarySum).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}元</span>
          <span style="font-size:16px">（其中：在职合计：{{ Number(workSalarySum).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}元</span>，
          <span style="font-size:16px">离休合计：{{ Number(retireSalarySum).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}元）</span><br>
          <span style="font-size:16px">在编人员：{{ personTotal }}人</span>
          <span style="font-size:16px">（其中：在职：{{ workTotal }}人</span>，
          <span style="font-size:16px">离休：{{ retireTotal }}人）</span>；
          <span style="font-size:16px">单位减员：{{ unitMinusTotal }}人</span>
          <span style="font-size:16px">（其中：在职：{{ workMinusTotal }}人</span>，
          <span style="font-size:16px">离休：{{ retireMinusTotal }}人）</span>；
          <span style="font-size:16px">单位增员：{{ unitPlusTotal }}人</span>
          <span style="font-size:16px">（其中：在职：{{ workPlusTotal }}人</span>，
          <span style="font-size:16px">离休：{{ retirePlusTotal }}人）</span>

        </el-col>

        <!-- <el-col v-if="tabPane === '-1'" :span="1">
          <el-link type="primary" @click="openAuditExplain">
            <span>退回说明</span>
          </el-link>
        </el-col> -->
      </el-row>
    </div>
    <!-- 表格部分 -->
    <el-table
      ref="singalTable"
      v-loading="listLoading"
      :data="list"
      :stripe="true"
      :height="tableHeight"
      fit
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
    >
      <template slot="empty">
        <tableEmpty />
      </template>
      <el-table-column prop="no" align="center" label="序号" fixed />
      <el-table-column label="工资月份" align="center" fixed>
        <template slot-scope="{row}">
          <span>{{ row.currentMonth }}</span>
        </template>
      </el-table-column>
      <el-table-column label="科室" align="center" fixed>
        <template slot-scope="{row}">
          <span>{{ row.deptId | deptNameFilter(that) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" fixed>
        <template slot-scope="{row}">
          <el-link
            v-if="row.personName !== '合计'"
            type="primary"
            @click="viewInfo(row)"
          >
            <span>{{ row.personName }}</span>
          </el-link>
          <span v-else>{{ row.personName }}</span>
        </template>
      </el-table-column>
      <el-table-column v-for="item in columnNames" :key="item" :prop="item" :label="item.split('_')[0] | salaryNameFilter(that)" align="center" width="130">
        <template slot-scope="{row}">
          <!--获取不带后缀的字段名-->
          <span v-if="!row.isOperate" style="float: right">{{ Number(row[item.split('_')[0]]).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}</span>
        </template>
      </el-table-column>

    </el-table>
    <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="handleFilter" />
    <PersonSalaryInfo ref="personSalaryInfo" />
    <el-dialog  v-dialogDrag  
      title="退回说明"
      :visible.sync="auditFormVisible"
      width="30%"
      max-height="500px"
    >
      <el-form
        ref="auditForm"
        :model="formData"
        label-position="right"
        label-width="120px"
        size="small"
      >
        <el-row>
          <el-col>
            <el-input
              v-model="formData.auditExplain"
              type="textarea"
              :rows="4"
              maxlength="500"
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col
            :span="16"
            style="text-align: right; margin-top:5%"
          >
            <el-button
              type="primary"
              :loading="saveExplainLoading"
              @click="saveExplain"
            >
              确定
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <ApprovalProcess ref="app" />

  </div>
</template>
<script>
import { querySalaryNameDict, queryColumnName, queryReallySendSalarySumAndPersonTotal } from '@/api/unitSalaryReport/unitSalaryReport'
import { queryUnitSalarySubmitReportPage } from '@/api/salaryReport/unitSubmit'
import { reportUnitSalary, reportRevokeUnitSalary, reportUnitSalaryBack } from '@/api/agencyVerify'
import { getDepartmentList } from '@/api/unitInformationMaintenance/internalOrganizationMaintenance'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import tableEmpty from '@/components/table/empty'
import PersonSalaryInfo from '@/components/personSalaryInfo/personSalaryInfo'
import { getAgencyVerifyByAgencyId } from '@/api/agencyVerify'
import ApprovalProcess from '@/components/ApprovalProcess/ApprovalProcess'

export default {
  name: 'Unit',
  components: { ApprovalProcess, Pagination, tableEmpty, PersonSalaryInfo },
  filters: {
    deptNameFilter(value, that) {
      const deptNames = that.deptNames
      for (const item of deptNames) {
        if (value === item.code) {
          return item.name
        }
      }
    },
    // 工资项滤器
    salaryNameFilter(value, that) {
      const salaryNames = that.salaryNames
      for (const item of salaryNames) {
        if (item.value === value) {
          return item.key
        }
      }
    }
  },
  props: ['tabPane', 'treeData'],
  data() {
    return {
      tableHeight: null,
      dialogQueryFormVisible: false,
      that: this,
      unitName: '预算单位',
      // salary: '0.00',
      reallySendSalarySum: '0.00',
      workSalarySum: '0.00',
      retireSalarySum: '0.00',
      personTotal: '0',
      workTotal: '0',
      retireTotal: '0',
      unitMinusTotal: '0',
      unitPlusTotal: '0',
      retireMinusTotal: '0',
      workMinusTotal: '0',
      retirePlusTotal: '0',
      workPlusTotal: '0',
      listQuery: {
        page: 1,
        limit: 200,
        flag: 0,
        salaryMonth: '',
        changes: '',
        personType: '',
        salaryType: '',
        personName: '',
        idenNo: '',
        agencyId: '',
        menuid: this.$router.currentRoute.meta.menuid
      },
      formData: { salaryType:''},
      changeAgencys: [{ 'code': '1', 'name': '有变动' }, { 'code': '0', 'name': '无变动' }],
      salaryTypes: [{ 'code': '0', 'name': '行政人员' }, { 'code': '1', 'name': '事业人员' }, { 'code': '11', 'name': '离休人员' }],
      total: 0,
      listLoading: false,
      list: [],
      columnNames: [], // 动态表头
      salaryNames: [],
      deptNames: [],
      agencyId: '',
      auditFormData: {
        auditExplain: ''
      },
      title1: '',
      saveExplainLoading: false,
      auditFormVisible: false,
      operateAgencyIds: [] // 操作单位id集合
    }
  },
  watch: {
    list(val) {
      this.doLayout()
    },
    treeData(val) {
      if (val && val.isleaf === '1') {
        this.agencyId = val.id
        this.listQuery.agencyId = val.id
        this.unitName = val.label.split('-')[1]
        this.handleTree(val)
      }
    }
  },
  created() {
    this.listQuery.flag = this.tabPane
    if (this.treeData && this.treeData.isleaf === '1') {
      this.agencyId = this.treeData.id
      this.listQuery.agencyId = this.treeData.id
      this.unitName = this.treeData.label.split('-')[1]
      this.initDict()
      this.getColumnNames()
      this.listQuery.page = 1
      this.getList()
      // this.selectSubmitSalarySum()
      this.getAgencyVerifyByAgencyId()
    }
  },
  mounted() {
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  methods: {
    // 退回
    auditReject() {
      this.operateAgencyIds = []
      this.operateCode = 'reject'
      this.formData = Object.assign({}, this.formData, '')
      this.formData.auditExplain = '不同意'
      this.title1 = '退回说明'
      this.auditFormVisible = true
    },
    // 统一保存
    saveExplain() {
      this.saveExplainLoading = true
      this.salaryBack()
    },
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 325
    },
    // 获取审核意见
    getAgencyVerifyByAgencyId() {
      getAgencyVerifyByAgencyId(this.listQuery.agencyId).then((response) => {
        this.auditFormData.auditExplain = response.data.auditExplain
      })
    },
    // 打开审核意见
    openAuditExplain() {
      this.auditFormVisible = true
    },
    // 动态获取表头
    getColumnNames() {
     Object.assign(this.listQuery, this.formData)
      this.listQuery['agencyId'] = this.agencyId
      queryColumnName(this.listQuery).then(response => {
        if (response.rscode === '100000') {
          this.columnNames = response.data
        } else {
          this.columnNames = []
          this.$message({
            showClose: true,
            message: '动态获取表头失败',
            type: 'error',
            duration: 0
          })
        }
      })
    },
    handleTree(data) {
      this.initDict()
      this.getColumnNames()
      this.listQuery.page = 1
      this.getList()
      // this.selectSubmitSalarySum()
      this.getAgencyVerifyByAgencyId()
    },
    // 分页查询
    handleFilter() {
      this.getList()
    },
    // 获取数据
    getList() {
      this.listLoading = true
      this.listQuery['agencyId'] = this.agencyId
      this.queryReallySendSalarySumAndPersonTotal()
      queryUnitSalarySubmitReportPage(this.listQuery).then(response => {
        if (response.rscode === '100000') {
          this.list = response.data.rows
          this.total = response.data.total
          this.listLoading = false
        } else {
          this.list = []
          this.total = 0
          this.listLoading = false
          this.$message({
            showClose: true,
            message: '查询单位工资编报列表失败',
            type: 'error',
            duration: 0
          })
        }
      })
    },
    // selectSubmitSalarySum() {
    //   queryReallySendSalarySumAndPersonTotal(this.listQuery.agencyId, 1).then(res => {
    //     if (res.rscode === '100000') {
    //       if (res.data === '') {
    //         this.salary = '0.00'
    //       } else {
    //         this.salary = Number(res.data.reallySendSalarySum).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
    //         // this.salary = res.data
    //       }
    //     } else {
    //       this.salary = '0.00'
    //     }
    //   })
    // },
    salarySubmit() {
      const tableData = this.$refs.singalTable.tableData
      if (tableData.length === 0) {
        this.$message({
          showClose: true,
          message: '没有未上报的数据',
          type: 'warning',
          duration: 4000
        })
        this.$emit('submitCallback')
        return
      }
      // this.$confirm('确定上报吗?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      this.formData['agencyId'] = this.agencyId
      this.formData['menuid'] = this.$router.currentRoute.meta.menuid
      this.formData['menuname'] = this.$router.currentRoute.meta.menuname
      // 将是否上报修改为1： 已上报
      reportUnitSalary(this.formData).then((response) => {
        this.$message({
          showClose: true,
          message: '上报成功',
          type: 'success',
          duration: 4000
        })
        this.$emit('submitCallback')
        this.handleFilter()
      }).catch(() => {
        this.$emit('submitCallback')
      })
      // }).catch(() => {
      //   this.$emit('submitCallback')
      // })
    },
    processnode() {
      this.$refs.app.getList(this.agencyId)
    },
    // 取消上报
    cancelSalarySubmit() {
      const tableData = this.$refs.singalTable.tableData
      if (tableData.length === 0) {
        this.$message({
          showClose: true,
          message: '没有撤销上报的数据',
          type: 'warning',
          duration: 4000
        })
        this.$emit('revokeSubmitCallback')
        return
      }
      // this.$confirm('确定撤销上报吗?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      this.formData['agencyId'] = this.agencyId
      this.formData['menuid'] = this.$router.currentRoute.meta.menuid
      this.formData['menuname'] = this.$router.currentRoute.meta.menuname
      // 将是否上报状态修改为0： 未上报
      reportRevokeUnitSalary(this.formData).then((response) => {
        this.$message({
          showClose: true,
          message: '撤销成功',
          type: 'success',
          duration: 4000
        })
        this.$emit('revokeSubmitCallback')
        this.handleFilter()
      }).catch(() => {
        this.$emit('revokeSubmitCallback')
      })
      // }).catch(() => {
      //   this.$emit('revokeSubmitCallback')
      // })
    },
    // 退回
    salaryBack() {
      const tableData = this.$refs.singalTable.tableData
      if (tableData.length === 0) {
        this.$message({
          showClose: true,
          message: '没有退回的数据',
          type: 'warning',
          duration: 4000
        })
        this.$emit('salaryBackCallback')
        return
      }
      // this.$confirm('确定退回吗?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      this.formData['agencyId'] = this.agencyId
      this.formData['menuid'] = this.$router.currentRoute.meta.menuid
      this.formData['menuname'] = this.$router.currentRoute.meta.menuname
      reportUnitSalaryBack(this.formData).then((response) => {
        this.$message({
          showClose: true,
          message: '退回成功',
          type: 'success',
          duration: 4000
        })
        this.auditFormVisible = false
        this.saveExplainLoading = false
        this.$emit('salaryBackCallback')
        this.handleFilter()
      }).catch(() => {
        this.$emit('salaryBackCallback')
      })
      // }).catch(() => {
      //   this.$emit('salaryBackCallback')
      // })
    },
    // 查看详情
    viewInfo(currenRow) {
      const personId = currenRow.personId.replace('noRepeat', '')
      this.$refs.personSalaryInfo.viewInfo(personId, undefined, this.agencyId)
    },
    // 初始化字典
    initDict() {
      querySalaryNameDict(this.listQuery).then(res => {
        if (res.rscode === '100000') {
          this.salaryNames = res.data
        } else {
          this.columnNames = []
          this.$message({
            showClose: true,
            message: '获取字典失败',
            type: 'error',
            duration: 0
          })
        }
      })
      getDepartmentList({ agencyId: this.agencyId }).then(res => {
        if (res.rscode === '100000') {
          this.deptNames = res.data
        } else {
          this.deptNames = []
          this.$message({
            showClose: true,
            message: '获取字典失败',
            type: 'error',
            duration: 0
          })
        }
      })
    },
    query() {
      this.dialogQueryFormVisible = true
    },
    handleQuery() {
      this.listQuery.page = 1
      // this.listQuery.limit = 10
      this.getList()
      this.dialogQueryFormVisible = false
    },
    queryReallySendSalarySumAndPersonTotal() {
      queryReallySendSalarySumAndPersonTotal(this.agencyId, 1)
        .then(res => {
          this.reallySendSalarySum = res.data.reallySendSalarySum
          this.workSalarySum = res.data.workSalarySum
          this.retireSalarySum = res.data.retireSalarySum
          this.personTotal = res.data.personTotal
          this.workTotal = res.data.workTotal
          this.retireTotal = res.data.retireTotal
          this.unitMinusTotal = res.data.unitMinusTotal
          this.unitPlusTotal = res.data.unitPlusTotal
          this.retireMinusTotal = res.data.retireMinusTotal
          this.workMinusTotal = res.data.workMinusTotal
          this.retirePlusTotal = res.data.retirePlusTotal
          this.workPlusTotal = res.data.workPlusTotal
        })
        .catch(() => {
          this.reallySendSalarySum = '0.00'
          this.workSalarySum = '0.00'
          this.retireSalarySum = '0.00'
          this.personTotal = '0'
          this.workTotal = '0'
          this.retireTotal = '0'
          this.unitMinusTotal = '0'
          this.unitPlusTotal = '0'
          this.retireMinusTotal = '0'
          this.workMinusTotal = '0'
          this.retirePlusTotal = '0'
          this.workPlusTotal = '0'
        })
    }
  }
}
</script>
